package com.yy.intercepter;

import cn.hutool.json.JSONUtil;
import com.yy.common.ErrorCode;
import com.yy.constant.UserConstant;
import com.yy.exception.BusinessException;
import com.yy.model.entity.User;
import com.yy.model.vo.LoginUserVO;
import com.yy.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Conditional;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;

import static com.yy.constant.UserConstant.USER_LOGIN_STATE;

@Component
@RequiredArgsConstructor
@Slf4j
public class UserRequestIntercepter implements HandlerInterceptor {

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        //从请求头获取 sessionId
        String sessionId = request.getHeader(UserConstant.USER_Seession_ID);
        //从redis取出登录态
        String jsonStr = (String) redisTemplate.opsForValue().get(USER_LOGIN_STATE + sessionId);
        try {
            User currentUser = JSONUtil.toBean(jsonStr, User.class);
            if (currentUser == null || currentUser.getId() == null) {
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
            }
            LoginUserVO loginUserVO = new LoginUserVO();
            BeanUtils.copyProperties(currentUser, loginUserVO);
            loginUserVO.setSessionId(sessionId);
            log.info("user服务的拦截器 从请求头获取 sessionId 成功!");
            //保存 登录态 到 ThreadLocal
            ThreadLocalUtil.setAttribute(loginUserVO);
            return true;
        } catch (Exception e) {
            log.error("user服务的拦截器 从请求头获取 sessionId 失败!");
            return true;
        }
    }
}
